package com.edu.modules.baseinfo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.edu.modules.baseinfo.dao.AccountDao;
import com.edu.modules.baseinfo.model.User;
import com.edu.modules.baseinfo.vo.LoginResultVo;
import com.edu.modules.baseinfo.vo.RegisterResultVo;
import com.edu.modules.baseinfo.vo.ResultVo;
import com.edu.modules.baseinfo.vo.StudentIdVo;
import com.edu.modules.comm.WXData;
import com.edu.modules.entity.TAccountEntity;
import com.sari.common.service.BaseService;
import com.sari.common.utils.DateUtils;
import com.sari.common.utils.IdGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Created by kwj on 2016/7/15.
 */
@Service
public class AccountService extends BaseService {

	private static Logger logger = LoggerFactory.getLogger(AccountService.class);

	@Autowired
	private AccountDao accountDao;

	public RegisterResultVo register(JSONObject param){

		String userName = param.getString("userName");
		String passWord = param.getString("passWord");
		String studentName = param.getString("studentName");
		String openId = param.getString("openId");

		String msg = null;
		boolean flag = false;
		String studentId = IdGen.uuid();
		int count = accountDao.getAccountByName(userName);
		if(count==1){
			msg = "用户已注册";
			return new RegisterResultVo(flag,null,null,msg);
		}

		int state = accountDao.addStudent(studentId,userName,studentName,openId,DateUtils.getDateTime());
		if (state==1){
			TAccountEntity account = new TAccountEntity();
			account.setId(IdGen.uuid());
			account.setUserName(userName);
			account.setPassWord(passWord);
			account.setUserRole("1");
			account.setUserId(studentId);
			account.setCreateTime(DateUtils.getDateTime());
			account.setUpdateTime(DateUtils.getDateTime());
			accountDao.saveObject(account);
			msg = "注册成功";
			flag = true;
		}else{
			msg = "注册失败";
			flag = false;
		}
		return new RegisterResultVo(flag,studentId,studentName,msg);
	}

	public LoginResultVo login(JSONObject param){

		String userName = param.getString("userName");
		String passWord = param.getString("passWord");
		String userRole = param.getString("userRole");

		String msg = null;
		User user = accountDao.getUser(userName,userRole);
		if (user == null) {
			msg = "用户不存在，请先注册！";
			return new LoginResultVo(false,null,userRole,null,msg);
		} else {
			if (user.getPassWord().equals(passWord)) {
				msg = "登录成功!";
				return new LoginResultVo(true,user.getUserId(),userRole,user.getUserName(),msg);
			} else {
				msg = "密码错误！";
				return new LoginResultVo(false,user.getUserId(),userRole,user.getUserName(),msg);
			}
		}
	}

	public ResultVo updatePwd(JSONObject param){

		String userId = param.getString("userId");
		String passWord = param.getString("passWord");

		accountDao.updatePwd(userId,passWord);
		return new ResultVo(true,"修改成功");
	}

	public String getMsgCode(String phone){

		String code;
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
		final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
		final String accessKeyId = "LTAIUC2Xw2T84ffr";//你的accessKeyId
		final String accessKeySecret = "GyIu6wjAxFxo3jnP6fMb9IvSx659WS";//你的accessKeySecret
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
				accessKeySecret);
		try {
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			SendSmsRequest request = new SendSmsRequest();
			request.setMethod(MethodType.POST);
			request.setPhoneNumbers(phone);
			request.setSignName("兮米在线");
			request.setTemplateCode("SMS_133990008");
			JSONObject codeObj = new JSONObject();
			code = String.valueOf((int)((Math.random()*9+1)*100000));
			codeObj.put("code",code);
			request.setTemplateParam(JSON.toJSONString(codeObj));

			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				return code;
			}
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return "";
	}

	public StudentIdVo getStudentId(String code){

		String openId = WXData.getOpenId(code);
		Map student = accountDao.getStudentId(openId);
		return new StudentIdVo(student,openId);
	}
}
